package com.letv.app.ljodfh.ui.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;

import org.xutils.common.util.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.List;

public class UIUtils {
    public static final String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sctv";
    private static float density = 1.0f;
    private static int screenWidth;
    private static int screenHeight;
    private static long lastClick;

    public static int dpToPx(Resources res, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                res.getDisplayMetrics());
    }

    public static float getDensity() {
        return density;
    }

    public static int getScreenWidth() {
        return screenWidth;
    }

    public static int getScreenHeight() {
        return screenHeight;
    }

    public static void initDisplayMetrics(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(metrics);
        density = metrics.density;
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;

    }

    /**
     * 将view转换为图片
     *
     * @param v
     * @return
     */
    public static Bitmap createViewBitmap(View v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }

    public static String initImagePath(Bitmap bitmap, String fileName) {
        String path = "";
        try {
            File fileNew = new File(dir);
            if (!fileNew.exists()) {
                fileNew.mkdirs();
            }
            File file = new File(fileNew, "/" + fileName);
//            if (!file.exists()) {
            file.createNewFile();
//            }
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            path = dir + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return path;
    }


    public static String initImagePathToGallery(Context mContext, Bitmap bitmap, String fileName) {
        String path = "";

        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        File fileNew;

        File file = null;

        try {
            fileNew = new File(galleryPath);
            if (!fileNew.exists()) {
                fileNew.mkdirs();
            }
            file = new File(fileNew, "/" + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            path = galleryPath + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }


        //通知相册更新
        MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
                bitmap, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        mContext.sendBroadcast(intent);


        return path;
    }


    // 用于控制快速连续点击事件只触发一次
    public static boolean fastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClick < 500) {
            return true;
        }
        lastClick = time;
        return false;
    }

    /**
     * dp转px
     *
     * @param dp
     * @return
     */
    public static int dip2px(Context context, int dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);
    }

    /**
     * px转换dip
     */
    public static int px2dip(Context context, int px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * px转换sp
     */
    public static int px2sp(Context context, int pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * sp转换px
     */
    public static int sp2px(Context context, int spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取sd位置
     */
    public static String getSDPath() {
        String sdExtra = System.getenv("EXTERNAL_STORAGE");
        if (!TextUtils.isEmpty(sdExtra)) {
            return sdExtra;
        }
        sdExtra = Environment.getExternalStorageDirectory().getAbsolutePath();
        if (!TextUtils.isEmpty(sdExtra)) {
            return sdExtra;
        }
        sdExtra = System.getenv("SECONDARY_STORAGE");
        if (!TextUtils.isEmpty(System.getenv(sdExtra))) {
            return sdExtra;
        }
        return null;
    }

    /**
     * 新闻详情 --数字处理
     *
     * @param count
     * @return
     */
    public static String getNumber(long count) {
        return "";
//        if (count > 1000000) {
//            return "100万+阅读";
//        } else if (count == 1000000) {
//            return "100万阅读";
//        } else {
//            if (count > 10000) {
//                //1万到100万之间
//                double num = (double) count / 10000;
////                DecimalFormat df=new DecimalFormat(".0");
////                String st=df.format(num);
//                BigDecimal b = new BigDecimal(num);
//                BigDecimal a = b.setScale(1, BigDecimal.ROUND_DOWN);
//                return a.toString() + "万阅读";
//            } else  {
//                return "" + count + "阅读";
//            }
//        }
    }

    /**
     * 新闻列表---数字处理
     *
     * @param count
     * @return
     */
    public static String getListNumber(long count) {
        return "";
//        if (count > 1000000) {
//            return "100万+阅读";
//        } else if (count == 1000000) {
//            return "100万阅读";
//        } else {
//            if (count > 10000) {
//                //1万到100万之间
//                double num = (double) count / 10000;
////                DecimalFormat df=new DecimalFormat(".0");
////                String st=df.format(num);
//                BigDecimal b = new BigDecimal(num);
//                BigDecimal a = b.setScale(1, BigDecimal.ROUND_DOWN);
//                return a.toString() + "万阅读";
//            } else {
//                return "" + count + "阅读";
//            }
//        }
    }

    public static String getDomain(String url) {
        String result = "";
        if (!TextUtils.isEmpty(url)) {
            int j = 0, startIndex = 0, endIndex = 0;
            for (int i = 0; i < url.length(); i++) {
                if (url.charAt(i) == '/') {
                    j++;
                    if (j == 2)
                        startIndex = i;
                    else if (j == 3)
                        endIndex = i;
                }

            }
            result = url.substring(0, endIndex);
        }
        return result;
    }

    /**
     * 获取字符串的长度，如果有中文，则每个中文字符计为2位
     *
     * @param value 指定的字符串
     * @return 字符串的长度
     */
    public static int textLength(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * 手机品牌的官方应用市场是否上架四川观察APP
     *
     * @return
     */
    public static boolean isExistApp() {
        boolean isExist = false;
        String manufacturer = Build.MANUFACTURER;
        if ("Huawei".equalsIgnoreCase(manufacturer)
                || "Xiaomi".equalsIgnoreCase(manufacturer)
                || "Meizu".equalsIgnoreCase(manufacturer)
                || "vivo".equalsIgnoreCase(manufacturer)
                || "samsung".equalsIgnoreCase(manufacturer)
                || "LENOVO".equalsIgnoreCase(manufacturer)
                || "OPPO".equalsIgnoreCase(manufacturer)) {
            isExist = true;
        }
        return isExist;
    }

    /**
     * 判断程序的运行在前台还是后台
     *
     * @param context
     * @return 0在未运行  大于0在运行
     */
    public static int isBackground(Context context) {
        try {
            ActivityManager activityManager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> listInfos = activityManager
                    .getRunningTasks(20);
            // 判断程序是否在栈顶
            if (listInfos.get(0).baseActivity.getClassName().equals("com.sctv.scfocus.ui.activities.SplashActivity")) {
                LogUtil.d("isBackground---com.sctv.scfocus正在运行 前台2");
                return 2;
            } else if (listInfos.get(0).topActivity.getPackageName().equals(context.getPackageName())) {
                LogUtil.d("isBackground---com.sctv.scfocus正在运行 前台1");
                return 1;
            } else {
//                // 判断程序是否在栈里
//                for (ActivityManager.RunningTaskInfo info : listInfos) {
//                    if (info.topActivity.getPackageName().equals(context.getPackageName())) {
//                        LogUtil.d("isBackground---com.sctv.scfocus正在运行 后台");
//                        return 1;
//                    }
//                }
                LogUtil.d("isBackground---com.sctv.scfocus未运行");
                return 0;// 栈里找不到，返回3
            }
        } catch (Exception e) {
            LogUtil.d("isBackground---com.sctv.scfocus未运行");
            return 0;
        }

    }

    public static String formatNumber(long count) {
        if (count > 1000000) {
            return "100万+阅读";
        } else if (count == 1000000) {
            return "100万阅读";
        } else {
            if (count > 10000) {
                //1万到100万之间
                double num = (double) count / 10000;
                BigDecimal b = new BigDecimal(num);
                BigDecimal a = b.setScale(1, BigDecimal.ROUND_DOWN);
                return a.toString() + "万阅读";
            } else {
                return "" + count + "阅读";
            }
        }
    }


    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName=null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }



}
